package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description: ReentrantLock实现线程安全
 * User: 王圆豪
 * Date: 2025-05-07
 * Time: 23:29
 */
public class Demo36 {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock reentrantLock = new ReentrantLock();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                try {
                    reentrantLock.lock();
                    count++;
                }finally {
                    reentrantLock.unlock();
                }
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                try {
                    reentrantLock.lock();
                    count++;
                }finally {
                    reentrantLock.unlock();
                }
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(100);
        System.out.println(count);
    }
}
